/**
 * @file      udp_server.c
 * @author    wzzlyzdn (wzzlyzdn@163.com)
 * @brief     udp 协议通信
 * @version   0.1
 * @date      2022-08-16
 * 
 * @copyright Copyright (c) 2022 wzzlyzdn
 * 
 * @note      历史记录: 
 *            - 
 * @warning   
 * @par       修改记录: 
 * <table>
 * <tr><th>date          <th>Version    <th>Author      <th>Description    </tr>
 * <tr><td>2022-08-16    <td> 0.1       <td>wzzlyzdn       <td>创建初始版本    </tr>
 * </table>
 */
#include "server.h"
#include "udp.h"
#include "server_client.h"


/**
 * @fn        int udp_server_main(UDP_INFO udpip)
 * @brief     udp 服务端函数
 * 
 * @param     [in] udpip     UDP_INFO 结构体，存储 ip port 信息
 * 
 * @return    int            错误返回 -1；正确返回 0；
 */
int udp_server_main(UDP_INFO udpip)
{
    DEBUG("---————————————————=☆=————————————————---\n");
    SOCKPACK sock_pack;
    pthread_t thread_udp_send;
    pthread_t thread_udp_recv;
    char buf[BUFFER_SIZE];
    int sockfd = UDP_Init(udpip, &sock_pack);
    int socklen = sizeof(sock_pack.addr);
    int ret_recv = -1;
    int ret_killa = 0;
    int ret_killb = 0;
    if (-1 == sockfd)
    {
        DEBUG("UDP 初始化失败\n");
        return -1;
    }

    ret_recv = recvfrom(sockfd, buf, BUFFER_SIZE, 0, (struct sockaddr *)&sock_pack.addr, &socklen);
    if (-1 == ret_recv)
    {
        DEBUG("初始化失败\n");
        return -1;
    }

    // filesend1.sockfd = sock_pack.sockfd;
    // filesend1.port = ntohs(sock_pack.addr.sin_port);
    // sprintf(filesend1.IP,"%s",inet_ntoa(sock_pack.addr.sin_addr));
    
    if (pthread_create(&thread_udp_recv, NULL, UDP_Recv, (void *)&sock_pack))
    {
        DEBUG("err : 接收线程创建失败\n");
        return -1;
    }
    if (pthread_create(&thread_udp_send, NULL, UDP_Send, (void *)&sock_pack))
    {
        DEBUG("err : 发送线程创建失败\n");
        return -1;
    }

    while (1)
    {
        ret_killa = pthread_kill(thread_udp_recv, 0);
        ret_killb = pthread_kill(thread_udp_send, 0);
        if (ESRCH == ret_killa || ESRCH == ret_killb)
        {
            break;
        }
    }
    DEBUG("---————————————————=☆=————————————————---\n");
    return 0;
    
}
